import 'dart:async';
import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:flutter/services.dart';

import 'package:flutter/material.dart';
import 'package:flutter_reader/dao/book_collect_data_manager.dart';
import 'package:flutter_reader/dao/login_data_manager.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_reader/tools/global_state.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_udid/flutter_udid.dart';
// import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provider/provider.dart';
import 'package:flutter_reader/tools/globals.dart' as globals;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:io' show Platform;

/// 墨水瓶（`InkWell`）可用时使用的字体样式。
final TextStyle _availableStyle = TextStyle(
  fontSize: 16.0,
  color: Color(0xffe53935),
);

/// 墨水瓶（`InkWell`）不可用时使用的样式。
final TextStyle _unavailableStyle = TextStyle(
  fontSize: 16.0,
  color: Colors.black26,
);

class LoginPage extends StatefulWidget {

  /// 倒计时的秒数，默认60秒。
  final int countdown;
  /// 用户点击时的回调函数。
  final Function onTapCallback;
  /// 是否可以获取验证码，默认为`false`。
  final bool available;

  LoginPage({
    this.countdown: 60,
    this.onTapCallback,
    this.available: true,
  });



  @override
  _LoginPageState createState() {
    return _LoginPageState();
  }
}


bool isPhone(String input) {
RegExp mobile = new RegExp(r"1[0-9]\d{9}$");
return mobile.hasMatch(input);
}

class _LoginPageState extends State<LoginPage> {

  String _udid = 'Unknown';

  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();

  /// 倒计时的计时器。
  Timer _timer;
  /// 当前倒计时的秒数。
  int _seconds;
  /// 当前墨水瓶（`InkWell`）的字体样式。
  TextStyle inkWellStyle = _availableStyle;
  /// 当前墨水瓶（`InkWell`）的文本。
  String _verifyStr = '获取验证码';

  @override
  void initState() {
    super.initState();
    // initPlatformState();
    _seconds = widget.countdown;
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(
        Duration(seconds: 1),
            (timer) {
          if (_seconds == 0) {
            _cancelTimer();
            _seconds = widget.countdown;
            inkWellStyle = _availableStyle;
            setState(() {});
            return;
          }
          _seconds--;
          _verifyStr = '已发送$_seconds'+'s';
          setState(() {});
          if (_seconds == 0) {
            _verifyStr = '重新发送';
          }
        });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  ///集成极光推送
  String debugLable = 'Unknown';
  // final JPush jpush = new JPush();

  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   try {
  //     jpush.addEventHandler(
  //       onOpenNotification: (Map<String, dynamic> message) async {
  //         print('通知栏打开');
  //         print("flutter onOpenNotification: $message");
  //         print("${message["extras"]}");
  //         print("${message["extras"]["cn.jpush.android.EXTRA"]}");
  //         Map aa = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
  //         print("${aa["bookID"]}");
  //         Navigator.push(context, MaterialPageRoute(
  //             builder: (context) => BookInfoPage(bookId: aa["bookID"],channel: "1",)
  //         ));
  //       },
  //     );
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  // }

  saveData(String sessionID) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString('login', 'true');
    preferences.setString('fullSessionID', sessionID);
    preferences.setString('LoginDate', DateTime.now().toIso8601String());
    print(DateTime.now().toIso8601String());
  }

  @override
  Widget build(BuildContext context) {

    final _hasLogin = Provider.of<GlobalModel>(context);

    // TODO: implement build
    return Scaffold(
          resizeToAvoidBottomPadding: true,
          body: SafeArea(
            child: SingleChildScrollView(
                reverse: true,
                child: Column(
                  children: <Widget>[
                    _topBar(),
                    Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(200)),
                      child: Center(
                          child: Image(
                            color: Color(0xffe53935),
                            width: ScreenUtil().setWidth(150),
                            image: AssetImage('images/fl_readBook.png'),
                          )
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: ScreenUtil().setWidth(20),top: ScreenUtil().setHeight(300)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Container(
                            width: ScreenUtil().setWidth(900),
                            child: Text('手机号码',
                              style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: ScreenUtil().setSp(50),
                                color: Color(0xffe53935),
                              ),),
                          ),
                          Container(
                            width: ScreenUtil().setWidth(900),
                            child: TextField(
                              controller: _phoneController,
                              decoration: InputDecoration(
                                hintText: '请输入手机号',
                              ),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(top: ScreenUtil().setHeight(100)),
                            width: ScreenUtil().setWidth(900),
                            child: Text('验证码',
                              style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: ScreenUtil().setSp(50),
                                color: Color(0xffe53935),
                              ),),
                          ),
                          Container(
                            width: ScreenUtil().setWidth(900),
                            child: Stack(
                              children: <Widget>[
                                Container(
                                  child: TextField(
                                    controller: _codeController,
                                    decoration: InputDecoration(
                                      hintText: '短信验证码',
                                    ),
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.only(top: ScreenUtil().setHeight(40), left: ScreenUtil().setWidth(600)),
                                  child: widget.available ?
                                  InkWell(
                                    child: Text(
                                      '  $_verifyStr  ',
                                      style: inkWellStyle,
                                    ),
                                    onTap: (_seconds == widget.countdown) ? () {
                                      print('点击');
                                      if(isPhone(_phoneController.text))
                                      {
                                        _startTimer();
                                        LoginDao.getAuthCode(globals.dateError, globals.uuid, int.parse(_phoneController.text)).then((value){
                                          print(value['success']);
                                          print(value['data']);
                                        });
                                        inkWellStyle = _unavailableStyle;
                                        _verifyStr = '$_seconds'+'s后';
                                        setState(() {});
                                      }
                                      else
                                      {
                                        toast('请输入正确的手机号');
                                      }
                                    } : (){
                                      ///倒计时未结束
                                      print('${_seconds}-------${widget.countdown}');
                                    },
                                  )
                                      : InkWell(
                                    child: Text(
                                      '  获取验证码  ',
                                      style: _unavailableStyle,
                                    ),
                                  ),
                                )
                              ],
                            ),
                          )
                        ],
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: ScreenUtil().setHeight(300)),
                      child: SizedBox(
                        width: ScreenUtil().setWidth(1000),
                        height: ScreenUtil().setHeight(150),
                        child: RaisedButton(
                          shape: RoundedRectangleBorder(
                              borderRadius: new BorderRadius.circular(30),
                              side: BorderSide(color: Colors.red)
                          ),
                          onPressed: (){
                            int.parse(_codeController.text).bitLength == 6 ? print('true') : print('false');
                            ///登录成功
                            LoginDao.goLogin(globals.dateError, globals.uuid, int.parse(_phoneController.text), int.parse(_codeController.text)).then((value){
                              print(value['success']);
                              print(value['data']);
                              if(value['success'] == true)
                              {
                                getUdid();
                                print("--------- 初始sessionID：${globals.fullSessionID}");
                                globals.fullSessionID = value['data']['SessionID'];
                                saveData(value['data']['SessionID']);
                                configDialog();
                                addRecommendBook();
                              }
                              else{
                                toast('登录失败');
                              }
                            });
                          },
                          color: Color(0xffe53935),
                          child: Text('登录',
                            style: TextStyle(color: Colors.white,
                                fontSize: ScreenUtil().setSp(55)),),
                        ),
                      ),
                    ),
                  ],
                )
            ),
          ),
        );
  }

  _topBar(){
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          IconButton(
            onPressed: (){
              Navigator.pop(context);
            },
            icon: Icon(
              Icons.chevron_left,
              color: Colors.black,
              size: ScreenUtil().setWidth(150),
            ),
          ),
        ],
      ),
    );
  }

  Future<void> getUdid() async {
    String udid;
    try {
      udid = await FlutterUdid.udid;
    } on
    PlatformException {
      udid = 'Failed to get UDID.';
    }
    _udid = udid;
    print('udid:${_udid}');
    globals.uuid = _udid;
  }

  addRecommendBook() async{
      print("添加推荐书");
      BookCollectDao.getForCollect("84101F8BF73334E10D400EAAE33FB71B");
      Future.delayed(const Duration(milliseconds: 100), (){
        BookCollectDao.getForCollect("34F73CA6C7AC6C6A2B54465AB251CAE0");
        Future.delayed(const Duration(milliseconds: 100),(){
          BookCollectDao.getForCollect("D2E941B0E38A097A110A920CB0B9C475");
        });
      });
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  configDialog() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //弹窗倒计时
    sharedPreferences.setInt("dialog", 2);
    sharedPreferences.setBool("goOther", false);
  }
}
